// 医院排班
import { useParams, useNavigate } from "react-router-dom"
import React, { useState, useEffect, Key } from "react"
import {
  Card,
  Row,
  Col,
  Tree,
  Tag,
  Pagination,
  Table,
  Button,
  message,
} from "antd"
import type { TreeProps } from "antd/lib/tree"
import {
  Department,
  DoctorScheduling,
  SchedulingOrder,
} from "@api/hospitalList"
// ts接口
import { IdeList } from "@api/hospitalList/model"

export default function Scheduling() {
  const { hoscode } = useParams()
  const navigate = useNavigate()

  // 科室数据
  const [deList, setDeList] = useState<IdeList>([])

  // 科室要展示的数据
  const [decodeList, setDecodeList] = useState<string[]>([])

  // 医院科室数据
  const [everyday, setEveryday] = useState<any>()

  // 科室code
  const [depcode, setDepcode] = useState<any>()

  // 分页器
  const [current, setCurrent] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(0)

  // 顶部的三个选择
  const [hosname, setHostname] = useState("")
  const [depname, setDepname] = useState("")
  const [workDate, setWorkDate] = useState("2022-04-28")

  async function onSelect(selectedKeys: any, info: any) {
    setDepname(info.node.depname) // info是当前选中的数据，重新保存数据渲染
    const depcode = selectedKeys[0] as string // selectedKeys是当前depcode

    try {
      const res = await SchedulingOrder(
        current,
        pageSize,
        hoscode as string,
        depcode
      )
      await setEveryday(res.bookingScheduleList) // 列表渲染
      const xxx = res.bookingScheduleList[0].workDate
      console.log(xxx)

      const yyy = await DoctorScheduling(hoscode as string, depcode, xxx)
    } catch (error) {
      // 如果没有数据则不显示，清空列表
      setEveryday([])
      setWorkDate("")
      message.error("暂无数据")
    }
  }

  // 挂载
  useEffect(() => {
    const xxx = async () => {
      // 调用函数获取数据
      const res = await getList()
      // 需要的参数在getList的返回值内，需要在getList之后再执行，使用await确定在执行完毕之后再调用
      const decode = res[0].children ? res[0].children[0].depcode : ""
      setDepcode(decode)
      SchedulingItem(current, pageSize, decode)
      SelectRoster(workDate)
    }
    xxx()
  }, [])

  // 排班选选择函数
  async function SelectRoster(workDate: string) {
    setWorkDate(workDate)
    const yyy = await DoctorScheduling(hoscode as string, depcode, workDate)
    setEveryday(yyy) // 点击获取新数据
    return yyy
  }
  // 封装函数，获取数据等
  async function getList() {
    const res = await Department(hoscode as any)
    // 给一级科室设置禁用，遍历加属性 disabled: true
    res.forEach((item: any) => (item.disabled = true))
    // 保存一级科室数据 拿到一级科室的数据并展开
    setDeList(res)
    setDecodeList(res.map((item) => item.depcode))

    // 添加时加个判断，防止值可能出现undefined的情况
    setDepname(res[0].children ? res[0].children[0].depname : "")
    return res
  }

  // 计算div高度，根据可视区比例计算
  // 窗口高度 - Header组件高度（64） - Card的上下padding（24*2） - p元素的高度（22）和下外边距（14） - 防止纵向滚动条（5）
  const divHeight = document.body.clientHeight - 64 - 34 - 24 * 2 - 22 - 14 - 5

  const [bookingScheduleList, setBookingScheduleList] = useState<any>([])

  // Tag 挂在获取科室信息，通过返回的数据拿到depcode，作为参数获取到Tag的数据
  const SchedulingItem = async (
    current: number,
    pageSize: number,
    depcode: string
  ) => {
    const res = await SchedulingOrder(
      current,
      pageSize,
      hoscode as string,
      depcode
    )
    setHostname(res.baseMap.hosname) // 保存hosname
    setTotal(res.total) // 存储total

    setBookingScheduleList(res.bookingScheduleList) // 将tag数据存储起来
    setWorkDate(res.bookingScheduleList[0].workDate)
    return res.bookingScheduleList
  }

  //table
  const columns: any = [
    {
      title: "序号",
      render: (a: any, b: any, index: number) => {
        return index + 1
      },
    },
    { title: "职称", dataIndex: "title" },
    { title: "号源时间", dataIndex: "workDate" },
    { title: "可预约数", dataIndex: "availableNumber" },
    { title: "剩余预约数", dataIndex: "reservedNumber" },
    { title: "挂号费(元)", dataIndex: "amount" },
    { title: "擅长技能", dataIndex: "skill" },
  ]

  return (
    <Card>
      <p>
        选择：{hosname} / {depname} / {workDate}
      </p>
      <Row gutter={20}>
        <Col span={5}>
          <div
            style={{
              height: divHeight,
              border: "1px solid #ccc",
              overflow: "auto",
            }}
          >
            <Tree
              // defaultExpandedKeys={["0-0-0", "0-0-1"]} // 默认要展开的键，树形结构是否展开
              onSelect={onSelect}
              treeData={deList as any} // 渲染的数据
              expandedKeys={decodeList} // 让树结构的指定节点展开的配置项
              // Tree组件,默认展示的是treeData中的title和key.但是我们的数据中没有,对应的是depname和depcode,
              // 所以设置fieldName.告诉Tree组件去选渲染指定的数据
              fieldNames={{
                title: "depname",
                key: "depcode",
              }}
            />
          </div>
        </Col>

        <Col span={19}>
          {/* 数据遍历渲染 */}
          {bookingScheduleList.map((item: any, index: number) => {
            return (
              <Tag
                color={workDate === item.workDate ? "green" : ""}
                style={{ cursor: "pointer" }}
                key={index}
                onClick={() => SelectRoster(item.workDate)}
              >
                <div>
                  {item.workDate} {item.dayOfWeek}
                </div>
                <div>
                  {item.availableNumber} / {item.reservedNumber}
                </div>
              </Tag>
            )
          })}

          <Pagination
            pageSizeOptions={[2, 5, 8]}
            total={total}
            showSizeChanger={true}
            current={current}
            pageSize={pageSize}
            style={{ marginTop: 10, marginBottom: 10 }}
            onChange={async (current, pageSize) => {
              const res = await SchedulingItem(current, pageSize, depcode)
              setWorkDate(res[0].workDate) // 与上面tag对应
              // 下面列表数据响应修改
              SelectRoster(res[0].workDate)
            }}
          />
          <Table
            columns={columns}
            dataSource={everyday}
            // 设置表格边框
            bordered
            // 默认有分页，不需要的话设置为false
            pagination={false}
          />
          <Button
            style={{ marginTop: 10 }}
            onClick={() => {
              navigate("/syt/hospital/hospitalList")
            }}
          >
            返回
          </Button>
        </Col>
      </Row>
    </Card>
  )
}
